package club.lovety.code.registrar.facroty;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;

public class MyFactoryBean<T> implements FactoryBean ,InitializingBean {


    private Class<T> myInterface;

    private  MyTemp myTemp = new MyTemp();

    public MyFactoryBean(){

    }

    public MyFactoryBean(Class<T> myInterface) {
        this.myInterface = myInterface;
    }

    @Override
    public Object getObject() throws Exception {
        return myTemp.getIntetface(this.myInterface);
    }

    @Override
    public Class<?> getObjectType() {
        return this.myInterface;
    }

    public void exec(){
        myTemp.addInterface(this.myInterface);
    }

    class MyTemp{

        private Map<Class,MyTempProxy> map = new HashMap<>();

        public void addInterface(Class className){
            map.put(className,new MyTempProxy(className));
        }

        public Object getIntetface(Class className){
            return map.get(className).getTempProxy();
        }

    }

    class MyTempProxy {

        public Class interfaceClass;

        public MyTempProxy(Class interfaceClass) {
            this.interfaceClass = interfaceClass;
        }

        public Object getTempProxy(){
            return Proxy.newProxyInstance(interfaceClass.getClassLoader(),new Class[]{interfaceClass},new MyProxy());
        }
    }


    class MyProxy implements InvocationHandler{

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            return "你已经使用代理返回内容了";
        }
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        exec();
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}
